<template>
  <div class="head">
    <textarea readonly="true" class="yuyinCon" placeholder="师爷，翻译翻译，什么叫做惊喜" :value="content"></textarea>
    <textarea
      readonly="true"
      class="yuyinCon"
      placeholder="No translation, just a surprise"
      :value="sendTextContent"
    ></textarea>
    <div class="yuyinBtn">
      <button
        :class="[{active:recordState == true }]"
        @touchstart="touchStart"
        @touchend="touchEnd"
      >
        <text v-if="recordState == false">按住 说话</text>
        <text v-else>松开 结束</text>
      </button>
    </div>
  </div>
</template>

<script>
import { navto } from "@/utils/util";
let plugin = requirePlugin("WechatSI");
const manager = plugin.getRecordRecognitionManager();
const backgroundAudioManager = wx.getBackgroundAudioManager();

export default {
  data() {
    return {
      currentTranslateVoice: "", // 当前播放语音路径
      sendTextContent: "", // 展示的语音内容
      //语音
      recordState: false, //录音状态
      content: "" //内容
    };
  },

  onShow() {
    this.getRecordAuth();
    console.log(backgroundAudioManager);
  },
  mounted() {
    //识别语音
    this.initRecord();
  },
  methods: {
    /**
     * 检验用户是否赋予录音权限
     */
    getRecordAuth() {
      wx.getSetting({
        success(res) {
          console.log("succ");
          console.log(res);
          if (!res.authSetting["scope.record"]) {
            wx.authorize({
              scope: "scope.record",
              success() {
                // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                console.log("succ auth");
              },
              fail() {
                wx.showModal({
                  title: "悲剧~",
                  content:
                    "您拒绝本小程序听您唠嗑的权利，想要继续唠嗑，只能删掉小程序重新关注了！",
                  success(res) {
                    wx.switchTab({ url: "/pages/home/main" });
                  }
                });
              }
            });
          } else {
            console.log("record has been authed");
          }
        },
        fail(res) {
          console.log("fail");
          console.log(res);
        }
      });
    },

    // 手动输入内容
    conInput(e) {
      this.content = e.detail.value;
    },
    //识别语音 -- 初始化
    initRecord() {
      const that = this;
      console.log("init");
      console.log(manager);
      // 有新的识别内容返回，则会调用此事件
      manager.onRecognize = function(res) {
        console.log("临时", res);
        that.content = res.result;
      };
      // 正常开始录音识别时会调用此事件
      manager.onStart = function(res) {
        console.log("成功开始录音识别", res);
      };
      // 识别错误事件
      manager.onError = function(res) {
        console.error("error msg", res);
      };
      //识别结束事件
      manager.onStop = res => {
        console.log("..............结束录音");
        console.log("录音临时文件地址 -->" + res.tempFilePath);
        console.log("录音总时长 -->" + res.duration + "ms");
        console.log("文件大小 --> " + res.fileSize + "B");
        console.log("语音内容 --> " + res.result);
        if (res.result == "") {
          wx.showModal({
            title: "提示",
            content: "听不清楚，请重新说一遍！",
            showCancel: false,
            success: function(res) {}
          });
          return;
        }
        that.content = res.result;
        if (res.result) {
          that.translateText(res.result);
        }
      };
      backgroundAudioManager.onPlay = res => {
        console.log("开始播放", res);
      };
      backgroundAudioManager.onStop = res => {
        console.log("停止播放", res);
      };
    },
    //语音  --按住说话
    touchStart(e) {
      console.log("start");
      //当开始说话的时候停止播放录音
      backgroundAudioManager.pause();
      this.recordState = true; //录音状态
      // 语音开始识别
      manager.start({
        lang: "zh_CN" // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
      });
    },
    //语音  --松开结束
    touchEnd() {
      console.log("end");
      this.recordState = false;
      // 语音结束识别
      manager.stop();
    },

    /**
     * 翻译
     */
    translateText(text) {
      plugin.translate({
        lfrom: "zh_CN",
        lto: "en_US",
        content: text,
        tts: true,
        success: resTrans => {
          console.log(resTrans);
          let passRetcode = [
            0, // 翻译合成成功
            -10006, // 翻译成功，合成失败
            -10007, // 翻译成功，传入了不支持的语音合成语言
            -10008 // 翻译成功，语音合成达到频率限制
          ];

          if (passRetcode.indexOf(resTrans.retcode) >= 0) {
            this.sendTextContent = resTrans.result;
            this.currentTranslateVoice = resTrans.filename;
            //翻译播放开始
            backgroundAudioManager.src = this.currentTranslateVoice;
            backgroundAudioManager.play();
          } else {
            console.warn("翻译失败", resTrans, item);
          }
        },
        fail: function(resTrans) {
          console.error("调用失败", resTrans, item);
        },
        complete: resTrans => {
          wx.hideLoading();
        }
      });
    }
  }
};
</script>

<style lang='less'>
.head {
  width: 90%;
  background-color: #fff;
  padding-top: 22rpx;
  margin: 0rpx auto;
  .yuyinCon {
    width: 675rpx;
    margin-top: 18rpx;
    margin-bottom: 38rpx;
    padding: 18rpx 0;
    text-align: center;
    border-radius: 25rpx;
    background-color: rgb(237, 245, 244);
  }
  .yuyinBtn {
    width: 250rpx;
    margin: 0 auto;
    button {
      background-color: rgb(176, 196, 228);
      &.active {
        background-color: rgb(89, 106, 151);
      }
    }
  }
}
</style>
